import Vue from "vue";
import $ from "jquery";
Vue.directive("title", {
  update: function(el, binding) {
    document.title = binding.value;
  }
});

let findChild = function(el, cb) {
  if ($(el).children(":not(span.v-highlight-span)").length) {
    $(el)
      .children()
      .each((x, node) => {
        if (cb) cb(node);
        findChild(node, cb);
      });
  }
};

Vue.directive("highlight", {
  componentUpdated: function(el, binding) {
    if (binding.value) {
      try {
        const modifiers = `g${binding.modifiers.m ? "m" : ""}`;
        const reg = new RegExp(binding.value, modifiers);
        if (binding.modifiers.log && console && console.log) {
          console.log(reg);
        }
        findChild(el, node => {
          let txt = $(node)
            .text()
            .trim();
          console.log(txt);
          if (txt) {
            txt = txt.replace(reg, word => {
              return `<span class='v-highlight-span'>${word}</span>`;
            });
            $(node).html(txt);
          }
        });
        return;
      } catch (error) {
        console.warn("Directive `highlight` error: ", error.message);
      }
    }
    $(el)
      .find("span.v-highlight-span")
      .each((i, node) => {
        $(node).after($(node).text());
        $(node).remove();
      });
    // el.innerHTML = el.innerHTML.replaceAll(binding.value, 'XXX');
  }
});
